<template>
  <div class="home_div">
    <div id="container" ref="mapContainer"></div>
  </div>
</template>

<script setup>
import AMapLoader from "@amap/amap-jsapi-loader";
import { shallowRef } from "@vue/reactivity";
import { ref, onMounted } from "vue";
import * as echarts from "echarts";
// 定义emit事件
const emit = defineEmits(['marker-click']);
const mapContainer = ref(null);
const map = shallowRef(null);
const AMap = shallowRef(null);
const back = ref(false);
const polygons = ref([]); // 区描边、遮罩
const district = shallowRef(null);
const polygon = shallowRef(null); // 市描边、遮罩
// 信息窗体相关
const infoWindow = shallowRef(null);
const currentInfoWindow = ref(null);

const width = 30;
const height = 30;
const markers = ref([]); // 用于存储标记对象
const locations = ref([]);

function getColorByAdcode(adcode) {
  let colors = {
    320312: "#456aed", // 铜山区
    320300: "#111111", // 徐州市
    320311: "#428ced",
    320322: "#a456e1",
    320302: "#123fee",
    320382: "#666eee",
    320305: "#963qde",
    320381: "#784eda",
    320324: "#456aed",
    320321: "#428ced",
  };
  return colors[adcode];
}

// 初始化遮罩
function initArea(areaName, isChildDraw) {
  district.value.search(areaName, function (status, result) {
    // 外多边形坐标数组和内多边形坐标数组
    var outer = [
      new AMap.value.LngLat(-360, 90, true),
      new AMap.value.LngLat(-360, -90, true),
      new AMap.value.LngLat(360, -90, true),
      new AMap.value.LngLat(360, 90, true),
    ];
    console.log(result);

    // 绘制遮罩
    var holes = result.districtList[0].boundaries;
    var pathArray = [outer];
    pathArray.push.apply(pathArray, holes);
    polygon.value = new AMap.value.Polygon({
      pathL: pathArray,
      strokeColor: "#00eeff",
      strokeWeight: 1,
      fillColor: "#020933",
      fillOpacity: 0.5,
    });
    polygon.value.setPath(pathArray);
    map.value.add(polygon.value);

    // 判断是否要绘制子区域
    if (isChildDraw) {
      // 将搜索层级设置为 街道/乡镇
      district.value.setLevel("district");
      for (let i = 0; i < result.districtList[0].districtList.length; i++) {
        areaPolyline(result.districtList[0].districtList[i].adcode);
      }
    }
  });
}

// 显示总览 - 改为铜山区
function showAllMap() {
  back.value = false;
  if (polygon.value) {
    // 清除遮罩
    map.value.remove(polygon.value);
  }
  // ====== 修改：改为铜山区 ======
  initArea("铜山区", true);
  // ====== 修改：铜山区中心坐标 ======
  map.value.setCenter([117.1833, 34.2667]);
  map.value.setZoom(12); // 适当放大显示区级
}

// 绘制区域描边
function areaPolyline(adcode) {
  if (polygons.value.length) {
    map.value.remove(polygons.value);
    polygons.value = [];
  }
  district.value.search(adcode, function (status, result) {
    // 绘制区域描边
    let bounds = result.districtList[0].boundaries;
    for (let i = 0; i < bounds.length; i++) {
      const color = getColorByAdcode(result.districtList[0].adcode);
      const polygon = new AMap.value.Polygon({
        path: bounds[i],
        strokeWeight: 4,
        fillOpacity: 0,
      });
      // 添加监听事件
      polygon.on("mouseover", () => {
        if (!back.value) {
          polygon.setOptions({
            fillOpacity: 0.7,
          });
        }
      });
      polygon.on("mouseout", () => {
        polygon.setOptions({
          fillOpacity: 0,
        });
      });
      polygons.value.push(polygon);
    }
    map.value.add(polygons.value);
  });
}

function ininMap() {
  // 这个配置很重要，必须设置，否则你的 行政服务搜索api无法使用生成回调
  window._AMapSecurityConfig = {
    securityJsCode: "fc522793449ed05764a01495e6647a8f",
  };
  AMapLoader.load({
    key: "6e62bcf47b2ea7d4d9b215f06d2728a4", //设置您的key
    version: "2.0",
    plugins: [
      "AMap.ToolBar",
      "AMap.Driving",
      "AMap.Polygon",
      "AMap.DistrictSearch",
      "AMap.Object3DLayer",
      "AMap.Object3D",
      "AMap.Polyline",
    ],
    AMapUI: {
      version: "1.1",
      plugins: [],
    },
    Loca: {
      version: "2.0.0",
    },
  })
    .then((AMap_res) => {
      AMap.value = AMap_res;
      map.value = new AMap_res.Map(mapContainer.value, {
        mapStyle: "amap://styles/grey",
        viewMode: "3D",
        zoom: 4,
        zooms: [10, 20],
        // ====== 修改：铜山区中心坐标 ======
        center: [117.1833, 34.2667],
        stylers: {
          color: "red",
        },
      });
      district.value = new AMap_res.DistrictSearch({
        subdistrict: 3, //获取边界返回下级行政区
        extensions: "all", //返回行政区边界坐标组等具体信息
        level: "district", // ====== 修改：改为区级查询 ======
      });
      mapContainer.value.style.backgroundColor = "transparent";

      // ====== 修改：改为铜山区 ======
      initArea("铜山区", true);
    })
    .catch((e) => {
      console.log(e);
    });
}

// 创建信息窗体内容
function createInfoWindowContent(res) {
  const statusColor = res.online ? '#00ff88' : '#ff4444';
  const statusText = res.online ? '在线' : '离线';

  return `
    <div class="vehicle-info-window" style="
      position: relative;
      background: linear-gradient(135deg, rgba(0, 20, 40, 0.95) 0%, rgba(0, 10, 20, 0.98) 100%);
      border: 2px solid ${statusColor};
      border-radius: 12px;
      padding: 15px;
      min-width: 280px;
      box-shadow: 
        0 0 30px rgba(0, 255, 136, 0.3),
        inset 0 0 20px rgba(0, 212, 255, 0.1);
      backdrop-filter: blur(15px);
      font-family: 'YJSZ', 'Arial', sans-serif;
      color: #ffffff;
    ">
      <div style="
        position: absolute;
        top: -2px;
        left: -2px;
        right: -2px;
        bottom: -2px;
        background: linear-gradient(45deg, 
          transparent 30%, 
          ${statusColor} 50%, 
          transparent 70%);
        border-radius: 12px;
        opacity: 0.4;
        animation: techGlow 2s ease-in-out infinite;
        z-index: -1;
      "></div>
      
      <div style="border-bottom: 1px solid rgba(0, 255, 255, 0.3); padding-bottom: 10px; margin-bottom: 10px;">
        <h3 style="
          margin: 0;
          color: #00ffff;
          font-size: 18px;
          text-shadow: 0 0 10px rgba(0, 255, 255, 0.8);
          letter-spacing: 1px;
        ">${res.vehicle_name || res.obj?.vehicle_name || '未知车辆'}</h3>
        <span style="
          display: inline-block;
          padding: 4px 8px;
          background: ${statusColor};
          border-radius: 4px;
          font-size: 12px;
          color: #000;
          font-weight: bold;
          margin-left: 10px;
        ">${statusText}</span>
      </div>
      
      <div style="font-size: 14px; line-height: 1.6;">
        <div style="margin-bottom: 8px;">
          <strong style="color: #00ffff;">🚗 车牌号：</strong>
          <span style="color: #e6f7ff;">${res.vehicle_name || res.obj?.vehicle_name || '未知'}</span>
        </div>
        <div style="margin-bottom: 8px;">
          <strong style="color: #00ffff;">🕐 卫星时间：</strong>
          <span style="color: #e6f7ff;">${res.gpstime || new Date().toLocaleString()}</span>
        </div>
        <div style="margin-bottom: 8px;">
          <strong style="color: #00ffff;">💨 速度：</strong>
          <span style="color: #e6f7ff;">${res.speed || '0'} km/h</span>
        </div>
        <div style="margin-bottom: 8px;">
          <strong style="color: #00ffff;">🧭 方位：</strong>
          <span style="color: #e6f7ff;">${res.dir_str || '未知'} (${res.dir || 0}°)</span>
        </div>
        <div style="margin-bottom: 8px;">
          <strong style="color: #00ffff;">📡 定位类型：</strong>
          <span style="color: #e6f7ff;">${res.location_mode_str || 'GPS'}</span>
        </div>
        <div style="margin-bottom: 8px;">
          <strong style="color: #00ffff;">🔥 点火状态：</strong>
          <span style="color: #e6f7ff;">${res.acc ? '已点火' : '未点火'}</span>
        </div>
        <div style="margin-bottom: 8px;">
          <strong style="color: #00ffff;">📍 经纬度：</strong>
          <span style="color: #e6f7ff; font-size: 12px;">
            ${Number(res.lng || 0).toFixed(6)}, ${Number(res.lat || 0).toFixed(6)}
          </span>
        </div>
        <div style="margin-bottom: 8px;">
          <strong style="color: #00ffff;">🔧 纠偏值：</strong>
          <span style="color: #e6f7ff; font-size: 12px;">
            Δ:${Number(res.glng || 0).toFixed(4)}, ${Number(res.glat || 0).toFixed(4)}
          </span>
        </div>
      </div>
      
      <div style="
        position: absolute;
        top: 10px;
        right: 10px;
        width: 8px;
        height: 8px;
        background: ${statusColor};
        border-radius: 50%;
        box-shadow: 0 0 10px ${statusColor};
        animation: blink 1.5s ease-in-out infinite;
      "></div>
    </div>
  `;
}

// 显示信息窗体
function showInfoWindow(marker, data) {
  // 关闭之前的信息窗体
  if (currentInfoWindow.value) {
    currentInfoWindow.value.close();
  }

  // 创建信息窗体
  if (!infoWindow.value) {
    infoWindow.value = new AMap.value.InfoWindow({
      isCustom: true,  // 使用自定义窗体
      closeWhenClickMap: true,
      offset: new AMap.value.Pixel(0, -30)
    });
  }

  // 设置内容并打开
  const content = createInfoWindowContent(data);
  infoWindow.value.setContent(content);
  infoWindow.value.open(map.value, marker.getPosition());

  currentInfoWindow.value = infoWindow.value;

  // 触发自定义事件
  emit('marker-hover', data);
}

function initMarkers(data) {
  locations.value = data;
  locations.value.forEach((res) => {
    // 车辆角度计算
    let dir = 0
    if (res.dir >= 0 && res.dir <= 45) {
      dir = 0
    } else if (res.dir >= 45 && res.dir < 90) {
      dir = 45
    } else if (res.dir >= 90 && res.dir < 135) {
      dir = 90
    } else if (res.dir >= 135 && res.dir < 180) {
      dir = 135
    } else if (res.dir >= 180 && res.dir < 225) {
      dir = 180
    } else if (res.dir >= 225 && res.dir < 315) {
      dir = 225
    } else if (res.dir >= 315 && res.dir < 345) {
      dir = 315
    } else if (res.dir >= 345 && res.dir < 360) {
      dir = 360
    }
    let marker = null;
    if (res.online) {
      marker = new AMap.value.Marker({
        position: [Number(res.lng) + Number(res.glng), Number(res.lat) + Number(res.glat)], // 经纬度数据
        map: map.value, // 将标记添加到地图上
        icon: new AMap.value.Icon({
          image: `http://139.129.18.80:8083/images/jiankong/pic/${res.obj.icon}/green_${dir}.png`,
          // image: `http://139.129.18.80:8083/${res.icon}`,
          size: new AMap.value.Size(40, 40), // 图标所处区域大小
          imageSize: new AMap.value.Size(40, 40),
          rotation: res.dir,
        }),
      });
    } else {
      marker = new AMap.value.Marker({
        position: [Number(res.lng) + Number(res.glng), Number(res.lat) + Number(res.glat)], // 经纬度数据
        map: map.value, // 将标记添加到地图上
        icon: new AMap.value.Icon({
          // image: `http://139.129.18.80:8083/images/jiankong/pic/${res.obj.icon}/green_${dir}.png`,
          image: `http://139.129.18.80:8083/${res.icon}`,
          size: new AMap.value.Size(width, height), // 图标所处区域大小
          imageSize: new AMap.value.Size(width, height),
          rotation: res.dir,
        }),
      });
    }

    // 创建科技感车牌号标签
    const labelContent = createTechLabel(res.obj.vehicle_name, res.online);
    marker.setLabel({
      content: labelContent,
      offset: new AMap.value.Pixel(10, -5), // 调整标签位置
    });

    // 添加鼠标悬浮事件 - 显示信息窗体
    marker.on('mouseover', (e) => {
      showInfoWindow(marker, res);
    });

    // 添加鼠标移出事件 - 关闭信息窗体
    marker.on('mouseout', () => {
      if (currentInfoWindow.value) {
        currentInfoWindow.value.close();
        currentInfoWindow.value = null;
      }
      console.log("==========================移出了")
    });

    // 添加点击事件
    marker.on('click', () => {
      emit('marker-click', res);
    });
    markers.value.push(marker); // 将标记对象保存到数组中，便于后续操作（如清除标记）
  });
}

// 创建科技感车牌号标签
function createTechLabel(vehicleName, isOnline) {
  const statusColor = isOnline ? '#00ff88' : '#ff4444';
  const glowColor = isOnline ? 'rgba(0, 255, 136, 0.6)' : 'rgba(255, 68, 68, 0.6)';

  return `
    <div class="tech-license-plate" style="
      position: relative;
      background: linear-gradient(135deg, rgba(0, 20, 40, 0.9) 0%, rgba(0, 10, 20, 0.95) 100%);
      border: 2px solid ${statusColor};
      border-radius: 8px;
      padding: 8px 12px;
      min-width: 120px;
      text-align: center;
      box-shadow: 
        0 0 20px ${glowColor},
        inset 0 0 10px rgba(0, 212, 255, 0.1);
      backdrop-filter: blur(10px);
      font-family: 'YJSZ', 'Arial', sans-serif;
      font-size: 14px;
      font-weight: bold;
      color: #ffffff;
      text-shadow: 
        0 0 5px ${statusColor},
        0 0 10px rgba(255, 255, 255, 0.8);
      letter-spacing: 2px;
      transform: perspective(500px) rotateX(15deg);
      transition: all 0.3s ease;
    ">
      <div style="
        position: absolute;
        top: -2px;
        left: -2px;
        right: -2px;
        bottom: -2px;
        background: linear-gradient(45deg, 
          transparent 30%, 
          ${statusColor} 50%, 
          transparent 70%);
        border-radius: 8px;
        opacity: 0.3;
        animation: techGlow 2s ease-in-out infinite;
        z-index: -1;
      "></div>
      <div style="
        position: absolute;
        top: 2px;
        left: 2px;
        right: 2px;
        bottom: 2px;
        background: linear-gradient(135deg, 
          rgba(0, 212, 255, 0.1) 0%, 
          transparent 50%, 
          rgba(0, 212, 255, 0.1) 100%);
        border-radius: 6px;
        z-index: -1;
      "></div>
      ${vehicleName}
    </div>
  `;
}

defineExpose({ initMarkers });

onMounted(() => {
  ininMap();
});
</script>

<style scoped>
.home_div {
  height: 95%;
  width: 95%;
  padding: 0px;
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  margin: auto;
}

#container {
  height: 100%;
  width: 100%;
  padding: 0px;
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  margin: auto;
}

.map-title {
  position: absolute;
  z-index: 1;
  width: 100%;
  height: 50px;
  background-color: rgba(27, 25, 27, 0.884);
  display: flex;
  justify-content: space-around;
  align-items: center;
}

h3 {
  z-index: 2;
  color: white;
}

.home_div {
  height: 95%;
  width: 95%;
  padding: 0px;
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  margin: auto;
}

#container {
  height: 100%;
  width: 100%;
  padding: 0px;
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  margin: auto;
}

.map-title {
  position: absolute;
  z-index: 1;
  width: 100%;
  height: 50px;
  background-color: rgba(27, 25, 27, 0.884);
  display: flex;
  justify-content: space-around;
  align-items: center;
}

h3 {
  z-index: 2;
  color: white;
}

/* 科技感标签动画 */
@keyframes techGlow {

  0%,
  100% {
    opacity: 0.3;
    transform: translateX(-100%);
  }

  50% {
    opacity: 0.6;
    transform: translateX(100%);
  }
}

/* 车牌号标签悬停效果 */
:deep(.amap-marker-label) {
  border: none !important;
  background: none !important;
  padding: 0 !important;
}

:deep(.tech-license-plate:hover) {
  transform: perspective(500px) rotateX(5deg) scale(1.05) !important;
  box-shadow:
    0 0 30px rgba(0, 255, 136, 0.8),
    inset 0 0 15px rgba(0, 212, 255, 0.2) !important;
}
</style>